<template>
    <transition name="el-zoom-in-center">
        <div id="content" class="SHZY-preview-main">
            <div class="SHZY-common-page-header">
                <el-page-header v-if="!this.$route.query.id" @back="goBack" :content="dataForm.code" />
                <h3 v-if="this.$route.query.id">检验批：{{ dataForm.code }}</h3>
                <div class="options">
                    <!-- <el-link
                        :icon="`icon-ym ${isFullscreen ? 'icon-ym-compress-screen' : 'icon-ym-full-screen'} SHZY-common-head-icon`"
                        :underline="false" @click="fullscreen()" style="margin-right: 10px;" /> -->
                    <el-button v-if="!readOnly" type="primary" @click="dataFormSubmit(1)" :loading="btnLoading">保
                        存</el-button>
                    <el-button v-if="!readOnly" type="primary" @click="dataFormSubmit(2)" :loading="btnLoading">提
                        交</el-button>
                    <el-button v-if="!this.$route.query.id" @click="goBack">取 消</el-button>
                </div>
            </div>
            <div :style="{ margin: '0 auto', width: '100%' }">
                <el-row :gutter="15" class="main">
                    <el-form ref="elForm" :disabled="readOnly">
                        <el-collapse-transition>
                            <el-descriptions v-if="isShow" :column="1" border>
                                <el-descriptions-item label="物料：" label-class-name="descriptions-label">
                                    {{ dataForm.materialCode + " " + dataForm.materialDes }}
                                </el-descriptions-item>
                                <el-descriptions-item label="工厂信息：" label-class-name="descriptions-label">
                                    <template v-if="dataForm.workshopId">
                                        {{ dataForm.workshopId }}
                                    </template>
                                    <template v-if="dataForm.teamId">
                                        {{ dataForm.teamId }}
                                    </template>
                                    <template v-if="dataForm.workshopSectionId">
                                        {{ dataForm.workshopSectionId }}
                                    </template>
                                    <template v-if="dataForm.stationId">
                                        {{ dataForm.stationId }}
                                    </template>
                                </el-descriptions-item>
                                <el-descriptions-item label="工序：" label-class-name="descriptions-label">
                                    {{ dataForm.processIdList }}
                                </el-descriptions-item>
                                <el-descriptions-item label="检验员：">
                                    {{ dataForm.employeeName }}
                                </el-descriptions-item>
                                <el-descriptions-item label="开始时间：">
                                    {{ shzy.toDate(dataForm.startTime, "yyyy-MM-dd HH:mm:ss") }}
                                </el-descriptions-item>
                                <el-descriptions-item label="结束时间：">
                                    {{ shzy.toDate(dataForm.endTime, "yyyy-MM-dd HH:mm:ss") }}
                                </el-descriptions-item>
                                <el-descriptions-item label="生产订单：">{{ dataForm.orderNo }}</el-descriptions-item>
                                <el-descriptions-item label="生产数量：">{{ dataForm.productionQty }}</el-descriptions-item>
                                <el-descriptions-item label="物料附件：">
                                    <template v-if="dataForm.materialFile.length">
                                        <ul class="el-upload-list el-upload-list el-upload-list--text">
                                            <li class="el-upload-list__item is-success"
                                                v-for="(file, index) in dataForm.materialFile" :key="file.fileId"
                                                :class="{ 'el-upload-list__item_detail': true }">
                                                <a class="el-upload-list__item-name" @click="handleClick(file)">
                                                    <i class="el-icon-paperclip"></i>{{ file.name }}
                                                </a>
                                            </li>
                                        </ul>
                                    </template>
                                </el-descriptions-item>
                                <el-descriptions-item label="检验方案附件：">
                                    <template v-if="dataForm.checkCardFile.length">
                                        <ul class="el-upload-list el-upload-list el-upload-list--text">
                                            <li class="el-upload-list__item is-success"
                                                v-for="(file, index) in dataForm.checkCardFile" :key="file.fileId"
                                                :class="{ 'el-upload-list__item_detail': true }">
                                                <a class="el-upload-list__item-name" @click="handleClick(file)">
                                                    <i class="el-icon-paperclip"></i>{{ file.name }}
                                                </a>
                                            </li>
                                        </ul>
                                    </template>
                                </el-descriptions-item>
                                <el-descriptions-item label="备注：">
                                    <el-input v-model="dataForm.remark" show-word-limit :style='{ "width": "100%" }'
                                        type='textarea' :autosize='{ "minRows": 4, "maxRows": 4 }' maxlength='500'>
                                    </el-input>
                                </el-descriptions-item>
                                <el-descriptions-item v-if="dataForm.status == 4" label="关闭原因：">{{ dataForm.closeDes
                                }}</el-descriptions-item>
                            </el-descriptions>
                        </el-collapse-transition>
                        <el-divider>
                            <el-button type="text" icon="el-icon-arrow-down" @click="isShow = true"
                                v-if="!isShow">展开</el-button>
                            <el-button type="text" icon="el-icon-arrow-up" @click="isShow = false" v-else>收起</el-button>
                        </el-divider>
                        <div class="SHZY-common-head">
                            <div>
                                <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>
                                <el-button type="text" icon="el-icon-delete" @click="handleBatchRemoveDel()"
                                    :loading="delBtnLoading">批量删除</el-button>
                            </div>
                            <div class="SHZY-common-head-right">
                                <el-dropdown @command="handleCommand">
                                    <span class="el-dropdown-link"><i class="el-icon-more"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item icon="el-icon-right" command="right"
                                            :disabled="direction == 'right'">回车右移</el-dropdown-item>
                                        <el-dropdown-item icon="el-icon-bottom" command="bottom"
                                            :disabled="direction == 'bottom'">回车下移</el-dropdown-item>
                                        <el-dropdown-item icon="el-icon-refresh-right"
                                            command="refresh">刷新数据</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </div>
                        <el-table v-loading="listLoading" :data="tableData" size="small" border
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="40">
                            </el-table-column>
                            <!-- <el-table-column type="index" width="50" label="序号" align="center" fixed="left" /> -->
                            <el-table-column prop="SamplingTypeDes" label="抽样方案" min-width="250">
                                <template slot-scope="scope">
                                    <template v-if="scope.row.SamplingTypeDes != ''">
                                        <el-tag size="medium">{{
                                            scope.row.SamplingTypeDes
                                        }}</el-tag>
                                        <el-tooltip effect="dark" content="点击修改抽样数量" placement="top">
                                            <el-tag size="small" effect="dark" style="margin-left: 5px;cursor: pointer;"
                                                @click="openEditSamplingQty(scope.row)">{{
                                                    scope.row.SamplingQty }}</el-tag>
                                        </el-tooltip>&nbsp;
                                        <el-tooltip effect="dark" content="点击添加检验项目" placement="top">
                                            <el-link icon="el-icon-edit" @click="addOrUpdateHandle(scope.row)"></el-link>
                                            <!-- <el-tag size="small" effect="plain" style="margin-left: 5px;cursor: pointer;"
                                                @click="addOrUpdateHandle(scope.row)"  ><i class="el-icon-plus"></i></el-tag> -->
                                        </el-tooltip>
                                    </template>
                                </template>
                            </el-table-column>
                            <el-table-column prop="InnspectionName" label="检验条目" min-width="300"
                                :show-overflow-tooltip="false">
                                <template slot-scope="scope">
                                    {{ scope.row.InnspectionName + "-" +
                                        scope.row.InnspectionEntryName
                                    }}
                                    <el-tag size="mini" v-if="scope.row.ReferTo == 'Y'" effect="plain" type="warning"
                                        style="margin-left: 5px;margin-top: 5px;">参</el-tag>
                                    <el-tag size="mini" v-if="scope.row.Exempt == 'Y'" effect="plain" type="success"
                                        style="margin-left: 5px;margin-top: 5px;">免</el-tag>
                                    <el-tag size="mini" v-if="scope.row.Destructiveness == 'Y'" effect="plain"
                                        type="warning" style="margin-left: 5px;margin-top: 5px;">破</el-tag>
                                    <el-tag size="mini" v-if="scope.row.AutoFlag == 'N'" effect="plain" type="warning"
                                        style="margin-left: 5px;margin-top: 5px;">手</el-tag>
                                    <el-tag size="mini" v-if="scope.row.AutoFlag == 'Y'" effect="plain" type="warning"
                                        style="margin-left: 5px;margin-top: 5px;">自</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="StandardValue" label="标准值" width="100">
                                <template slot-scope="scope">
                                    {{ scope.row.StandardValue == 0 ? "" : scope.row.StandardValue + scope.row.Unit }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="Remarks" label="规格标准" min-width="200" :show-overflow-tooltip="true">
                                <template slot-scope="scope">
                                    <template v-if="scope.row.QuantitativeStandards == '1'">
                                        {{ scope.row.MinimumValue + scope.row.Unit + " ~ " + scope.row.MaximumValue +
                                            scope.row.Unit
                                        }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '2'">
                                        &lt;{{ scope.row.StandardValue + scope.row.Unit }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '3'">
                                        &gt;{{ scope.row.StandardValue + scope.row.Unit }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '4'">
                                        ={{ scope.row.StandardValue + scope.row.Unit }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '5'">
                                        &le;{{ scope.row.StandardValue + scope.row.Unit }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '6'">
                                        &ge;{{ scope.row.StandardValue + scope.row.Unit }}
                                    </template>
                                    <template v-if="scope.row.QuantitativeStandards == '7'">
                                        {{ (scope.row.StandardValue - scope.row.LowerDeviation) + scope.row.Unit + " ~ " +
                                            (scope.row.StandardValue + scope.row.UpperDeviation) + scope.row.Unit }}
                                    </template>
                                    {{ scope.row.Remarks }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="Parameter" label="参数" width="50" align="center">
                                <template slot-scope="scope">
                                    <span style="cursor: pointer;" @click="openParameter(scope.row)"><i
                                            class="el-icon-setting" style="font-size: 16px;"></i></span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="Status" label="状态" width="105">
                                <template slot-scope="scope">
                                    <el-switch v-if="scope.row.Type == 'qualitative'" v-model="scope.row.defectStatus"
                                        :disabled="scope.row.defectQty > 0" class="switchStyle" active-text="无缺陷"
                                        inactive-text="有缺陷" active-color="#DCDFE6" inactive-color="#ff4949" active-value="N"
                                        inactive-value="Y">
                                    </el-switch>
                                    <el-tag v-if="scope.row.Type == 'ration' && scope.row.Status == 'OK'"
                                        type="success">合格</el-tag>
                                    <el-tag v-if="scope.row.Type == 'ration' && scope.row.Status == 'NG'"
                                        type="danger">不合格</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column v-for="(item, index) in customColumnList" :label="item.columnName" :key="index"
                                :prop="'column' + item.index" min-width="100">
                                <template slot="header" slot-scope="scope">
                                    <el-input v-model="item.columnName" :key="index" size="mini" />
                                </template>
                                <template slot-scope="scope">
                                    <template v-if="index < scope.row.SamplingQty">
                                        <el-input v-if="scope.row.Type == 'ration'" :id="'id_' + index + scope.$index"
                                            @keyup.enter.native="handleEnter()" @focus="handleFocus(index, scope.$index)"
                                            @change="handleChange(scope.row, scope.row['column' + item.index])"
                                            v-model="scope.row['column' + item.index].value" size="mini"
                                            oninput="value=value.replace(/[^0-9.]/g,'').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')"
                                            :suffix-icon="handleSuffixIcon(scope.row['column' + item.index].status)" />
                                        <i v-if="scope.row.Type == 'qualitative' && scope.row.defectStatus == 'N'"
                                            class="el-icon-check" style="font-size: 16px;"></i>
                                        <span v-if="scope.row.Type == 'qualitative' && scope.row.defectStatus == 'Y'"
                                            style="cursor: pointer;" @click="addDefect(scope.row.Id, item.index)">
                                            <i class="el-icon-more"
                                                :style="'font-size: 16px;' + (scope.row['column' + item.index].defectQty > 0 ? 'color:red' : '')"></i>
                                        </span>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                        <Defect v-if="defectVisible" ref="Defect" @refresh="initItemData()" />
                        <Parameter v-if="parameterVisible" ref="Parameter" />
                        <SamplingQty v-if="samplingQtyVisible" ref="SamplingQty" @refresh="initItemData()" />
                        <AddItem v-if="addItemVisible" ref="AddItem" @refresh="initItemData()" />
                    </el-form>
                </el-row>
            </div>
            <MessageBoard ref="MessageBoard" />
            <el-button type="primary" icon="el-icon-arrow-left" title="留言板" size="large" class="setting-btn" @click="$refs.MessageBoard.init(dataForm.id,dataForm.code,dataForm.employeeId,'IPQC')"></el-button>
        </div>
    </transition>
</template>
<script>

import { mapGetters } from "vuex"
import { getDownloadUrl } from '@/api/common'
import { getIpqcInspectionlotInfo, getIpqcInspectionitemList, saveIpqcInspectionlot, submitIpqcInspectionlot, delIpqcInspectionitemBatch } from '@/api/q1/business/ipqcInspectionLot'
import Defect from './Defect'
import Parameter from './Parameter'
import SamplingQty from './SamplingQty'
import AddItem from './AddItem'
import MessageBoard from '@/views/q1/business/messageBoard'
export default {
    components: { Defect, Parameter, SamplingQty, AddItem,MessageBoard },
    props: [],
    data() {
        return {
            isFullscreen: false,
            btnLoading: false,
            loading: false,
            visible: false,
            isShow: true,
            dataForm: {
                id: "",
                code: "",
                inspectionCode: "",
                date: "",
                type: "",
                inspectType: "",
                workshopId: "",
                teamId: "",
                workshopSectionId: "",
                stationId: "",
                processIdList: "",
                materialCode: "",
                materialDes: "",
                productionQty: "",
                employeeId:"",
                employeeCode: "",
                employeeName: "",
                orderNo: "",
                remark: "",
                status: "",
                closeDes: "",
                closeDate: "",
                judgeStatus: "",
                udNo: "",
                decision: "",
                decisionName: "",
                destructivenessQty: "",
                receiveQty: "",
                decisionDesc: "",
                overdue: "",
                enabledMark: "",
                startTime: "",
                endTime: "",
                materialFile: [],
                checkCardFile: [],
            },
            tableData: [],
            customColumnList: [],
            listLoading: false,
            defectVisible: false,
            parameterVisible: false,
            samplingQtyVisible: false,
            addItemVisible: false,
            currentCoordinate: [],
            direction: "right",
            readOnly: false,
            confirmed: "",// 二次确认
            delBtnLoading: false,
            multipleSelection: [],
        }
    },
    computed: {
        ...mapGetters(['userInfo'])
    },
    watch: {},
    created() {
        if (this.$route.query.id) {
            this.init(this.$route.query.id)
        }
    },
    mounted() {
    },
    methods: {
        goBack() {
            this.$emit('refresh')
        },
        init(id, readOnly) {
            this.readOnly = readOnly || false;
            this.dataForm.id = id || 0;
            this.visible = true;
            this.$nextTick(() => {
                if (this.dataForm.id) {
                    getIpqcInspectionlotInfo(this.dataForm.id).then(res => {
                        this.dataForm = res.data;
                        if (this.dataForm.status > 1) {
                            this.readOnly = true
                        }
                        if (this.userInfo.userAccount != "admin" && this.userInfo.userAccount != this.dataForm.employeeCode) {
                            this.readOnly = true
                        }
                        this.initItemData();
                    })
                }
            });
        },
        initItemData() {
            this.listLoading = true;
            getIpqcInspectionitemList(this.dataForm.code).then(res => {
                this.tableData = res.data.list
                this.customColumnList = res.data.customColumnList
                this.listLoading = false
            })
        },
        fullscreen() {
            const element = document.getElementById('content');
            if (this.isFullscreen) {
                // 退出全屏
                document.exitFullscreen();
                this.isFullscreen = false
            } else {
                // 全屏
                element.requestFullscreen()
                this.isFullscreen = true
            }
        },
        handleCommand(command) {
            if (command == "refresh") {
                this.initItemData()
            } else {
                this.direction = command
            }
        },
        handleEnter() {
            if (this.direction == "right") {
                let id = "id_" + (this.currentCoordinate[0] + 1) + this.currentCoordinate[1]
                const obj = document.getElementById(id)
                if (obj) {
                    obj.focus()
                }
            } else {
                let id = "id_" + this.currentCoordinate[0] + (this.currentCoordinate[1] + 1)
                const obj = document.getElementById(id)
                if (obj) {
                    obj.focus()
                }
            }
        },
        handleFocus(x, y) {
            this.currentCoordinate = [x, y]
        },
        handleChange(row, column) {
            let _value = parseFloat(column.value)
            if (row.QuantitativeStandards == "1") {
                column.status = "NG"
                if (row.MinimumValue <= _value && _value <= row.MaximumValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "2") {
                column.status = "NG"
                if (_value < row.StandardValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "3") {
                column.status = "NG"
                if (_value > row.StandardValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "4") {
                column.status = "NG"
                if (_value == row.StandardValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "5") {
                column.status = "NG"
                if (_value <= row.StandardValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "6") {
                column.status = "NG"
                if (_value >= row.StandardValue) {
                    column.status = "OK"
                }
            } else if (row.QuantitativeStandards == "7") {
                column.status = "NG"
                if ((row.StandardValue - row.LowerDeviation) <= _value && _value <= (row.StandardValue + row.UpperDeviation)) {
                    column.status = "OK"
                    if (_value > row.StandardValue) {
                        column.status = "UP"
                    } else if (_value < row.StandardValue) {
                        column.status = "Down"
                    }
                }
            }
        },
        handleSuffixIcon(status) {
            if (status == "Down") {
                return "el-icon-bottom"
            } else if (status == "UP") {
                return "el-icon-top"
            } else if (status == "OK") {
                return "el-icon-check"
            } else if (status == "NG") {
                return "el-icon-close"
            } else {
                return ""
            }
        },
        dataFormSubmit(status) {
            if (this.tableData.length == 0) {
                this.$message({
                    type: 'error',
                    message: '检验项目不能为空，请确认',
                    duration: 1500,
                })
                return
            }
            this.dataForm.status = status;
            this.dataForm.dataArray = this.tableData;
            this.dataForm.columnArray = this.customColumnList;

            this.dataForm.confirmed = this.confirmed;
            this.btnLoading = true;
            const formMethod = status == 2 ? submitIpqcInspectionlot : saveIpqcInspectionlot;
            formMethod(this.dataForm).then((res) => {
                this.btnLoading = false;
                if (status == 2 && res.code == 200) {
                    if (res.data.confirm == "Y") {
                        // 二次确认
                        this.$confirm('当前检验批已填写破坏性数量，是否已确认填写正确？', '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.confirmed = "Y";
                            this.dataFormSubmit(2);
                        });
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                if (this.dataForm.status > 1) {
                                    this.readOnly = true
                                    this.$emit('refresh', true)
                                }
                            }
                        })
                    }
                } else {
                    this.$message({
                        message: res.msg,
                        type: 'success',
                        duration: 1000,
                        onClose: () => {
                            this.init(this.dataForm.id, false)
                        }
                    })
                }
            }).catch((res) => {
                this.btnLoading = false;
            })

        },
        // 添加缺陷
        addDefect(id, index) {
            this.defectVisible = true
            this.$nextTick(() => {
                this.$refs.Defect.init(id, index, this.readOnly)
            })
        },
        // 打开其他参数
        openParameter(row) {
            this.parameterVisible = true
            this.$nextTick(() => {
                this.$refs.Parameter.init(row, this.readOnly)
            })
        },
        // 打开编辑抽样数量
        openEditSamplingQty(row) {
            if (row.SamplingType == "1" || row.SamplingType == "4") {
                this.$message({
                    type: 'error',
                    message: '只有固定抽样，固定比例，执行时自行设置才可修改抽样数量',
                    duration: 1500,
                })
                return
            }
            this.samplingQtyVisible = true
            this.$nextTick(() => {
                this.$refs.SamplingQty.init(row.Code, row.SampleId, row.SamplingQty, this.dataForm.productionQty)
            })
        },
        // 新增检验项目
        addOrUpdateHandle(row) {
            this.addItemVisible = true
            this.$nextTick(() => {
                this.$refs.AddItem.init(this.dataForm.code, this.dataForm.productionQty, row)
            })
        },
        // 批量删除检验项目
        handleBatchRemoveDel() {
            if (!this.multipleSelection.length) {
                this.$message({
                    type: 'error',
                    message: '请选择一条数据',
                    duration: 1500,
                })
                return
            }
            const ids = this.multipleSelection
            this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
                type: 'warning'
            }).then(() => {
                this.delBtnLoading = true
                delIpqcInspectionitemBatch(ids).then(res => {
                    this.delBtnLoading = false
                    this.$message({
                        type: 'success',
                        message: res.msg,
                        onClose: () => {
                            this.initItemData()
                        }
                    });
                })
            }).catch(() => {
                this.delBtnLoading = false
            })
        },
        handleSelectionChange(val) {
            const res = val.map(item => item.Id)
            this.multipleSelection = res
        },
        handleClick(file) {
            // 点击下载文件
            if (!file.fileId) return
            getDownloadUrl('annex', file.fileId).then(res => {
                this.shzy.downloadFile(res.data.url)
            })
        },
    }
}
</script>
<style lang="scss" >
.el-dropdown-link {
    cursor: pointer;
}

.descriptions-label {
    width: 110px;
}

.descriptions-content {
    width: 200px;
}

.el-table {
    .el-icon-top:before {
        color: #E6A23C;
        font-size: 16px;
    }

    .el-icon-bottom:before {
        color: #E6A23C;
        font-size: 16px;
    }

    .el-icon-check:before {
        color: #67C23A;
        font-size: 16px;
    }

    .el-icon-close:before {
        color: red;
        font-size: 16px;
    }
}

.switchStyle {
    height: 30px;
    line-height: 30px;

    .el-switch__label {
        width: 80px !important;
        height: 30px !important;
        position: absolute;
        border-radius: 15px;
        display: none;
        color: #fff;

        &--left {
            z-index: 9;
            left: 26px;
            top: 1px;
            color: #fff
        }

        &--right {
            z-index: 9;
            left: 5px;
            top: 1px;
        }

        &.is-active {
            display: block;
        }
    }

    .el-switch__core {
        width: 80px !important;
        height: 30px !important;
        border-radius: 15px;

        &::after {
            top: 4px;
            width: 20px;
            height: 20px;
            border-radius: 15px;
        }
    }

    .is-checked {
        .el-switch {
            &__core {
                &::after {
                    margin-left: -21px;
                }
            }
        }
    }
}
</style>
<style lang="scss" scoped>
.setting-btn {
    position: absolute;
    top: 200px;
    right: -10px;
    height: 40px;
    width: 40px;
    text-align: center;
    padding: 0;
    border-radius: 20px 0 0 20px;
    z-index: 100;

    >>>i {
        font-size: 20px;
        font-weight: 580;
    }
}
</style>
    
    